//定义路由
import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter)


//导出页面组件
import Home from '@/views/Home.vue'
import Car from '@/views/Car.vue'
import Category from '@/views/Category.vue'
import User from '@/views/User.vue'
import Topic from '@/views/Topic.vue'
import Search from '@/views/Search.vue'
import Detail from '@/views/Detail.vue'
import Classification from '@/views/Classification.vue'




//
const routes = [{
        path: '/',
        redirect: '/home',

    }, {
        path: '/home',
        component: Home,
        name: 'home',
        meta: { isshowtanbar: true },
        // 二级路由 搜索页
        children: [{
            path: 'search',
            component: Search,
            name: 'search',
            meta: { isshowtanbar: false },
        }]
    },
    { path: '/car', component: Car, name: 'car', meta: { isshowtanbar: true }, },
    { path: '/category', component: Category, name: 'category', meta: { isshowtanbar: true }, },
    { path: '/user', component: User, name: 'user', meta: { isshowtanbar: true }, },
    { path: '/topic', component: Topic, name: 'topic', meta: { isshowtanbar: true }, },
    { path: '/detail', component: Detail, name: 'detail', meta: { isshowtanbar: false }, },
    { path: '/classification', component: Classification, name: 'classification', meta: { isshowtanbar: false }, },

]







//
const router = new VueRouter({
    routes,
    mode: 'history'
})

// 创建路由导航前置守卫
// 监控全局所有路由导航,项目中只要需要路由,就会执行守卫
router.beforeEach((to, from, next) => {
    // 判断当访问购物车页时,用户是否登录,未登录跳转到user页
    if (to.path == "/car") {
        // 表示访问购物车页
        let token = localStorage.getItem("token"); //返回值 字符串 或 null
        if (token) {
            // 说明本地有token 是登录状态
            next();
        } else {
            // 说明本地没有token
            // 提示跳转到登录页
            Vue.prototype.$dialog
                .confirm({
                    title: "您未登录",
                    message: "需要登录请点击确定",
                    // theme: 'round-button',
                })
                .then(() => {
                    next("/user");
                })
                .catch(() => {
                    //点击取消
                });
        }
    } else {
        next();
    }
});

// 如下代码解决路由重复点击报错  (该报错vue-router3有  vue-router4没有)
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

//导出
export default router